package com.example.entity.delay;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author ChenXiaoBin
 * on 2019-06-25
 */
public class DelayedVo<T> implements Delayed{

    // 到期时间，单位为毫秒，实际计算为纳秒
    private long activeTime;

    // 业务数据
    private T data;

    // activeTime:过期时长，单位为毫秒
    public DelayedVo(long activeTime, T data) {
        super();
        this.activeTime = TimeUnit.NANOSECONDS.convert(activeTime, TimeUnit.MILLISECONDS) + System.nanoTime();
        this.data = data;
    }

    public long getActiveTime() {
        return activeTime;
    }

    public T getData() {
        return data;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.activeTime - System.nanoTime(), TimeUnit.NANOSECONDS);
    }


    @Override
    public int compareTo(Delayed delayed) {
        long excessTime = getDelay(TimeUnit.NANOSECONDS) - delayed.getDelay(TimeUnit.NANOSECONDS);
        return excessTime == 0 ? 0 : ((excessTime < 0 ? -1 : 1));
    }
}
